package com.baomidou.springwind.baidu;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.math.BigDecimal;

/**
 * Created by demo on 2017/8/7.
 */
public class Geocoder {
    private static final String AK = "NURx5GUAQ1IBZVBMCQSpYppRsDdTpbxG";

    public static JSONObject getAddressComponent(BigDecimal lng, BigDecimal lat) {
        String url = String.format("http://api.map.baidu.com/geocoder/v2/?location=%s,%s&output=json&pois=1&ak=%s", lat, lng, AK);
        CloseableHttpClient client = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = client.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = httpResponse.getEntity();
                String text = EntityUtils.toString(httpEntity);//取出应答字符串
                JSONObject json = JSONObject.parseObject(text);
                if ("0".equals(json.getString("status"))) {
                    return json.getJSONObject("result");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
